#encoding=utf-8
__author__ = 'Administrator'
import time,sys,os,json
sys.path.append('mymd')
from mymd import sql,ch_tpp,session
import main_men
#import tornado.autoreload
#import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import tornado.template
import tornado.httpclient
import tornado.gen
from session import SessionHandler
from redis import client

from beaker.middleware import SessionMiddleware
from tornado.options import define, options
#------------------------------------------------------------------
#userupdate_res=[]
#hostupdate_res=[]
#------------------------------------------------------------------
#define("port", default=80, help="run on the given port", type=int)
#实例化sql类
mysql=sql.Mysql('127.0.0.1','root','123456','kkk')

class myapp(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/login", login_Handler),  (r"/logout", logout_Handler),
            (r"/", MainHandler), (r"/logs", Logs_Handler),
            (r"/rsync",Rsync_Handler),(r"/rsync/file",Rsync_file_Handler),(r"/rsync/dir",Rsync_dir_Handler),
            (r"/zdh",Zdh_Handler),(r"/zdh/server",Zdh_server_Handler),(r"/zdh/docker",Zdh_docker_Handler),
            (r"/check", Check_Handler),(r"/check/host", CheckHost_Handler),(r"/check/info", CheckInfo_Handler),
            (r"/users", Users_Handler),(r"/users/add", UsersAdd_Handler),(r"/users/update", UsersUpdate_Handler),
            (r"/users_group", Users_group_Handler),(r"/users_group/update", Users_groupUpdate_Handler),
            (r"/hosts", Hosts_Handler),(r"/hosts/add", HostsAdd_Handler),(r"/hosts/update", HostsUpdate_Handler),
            (r"/hosts_group", Hosts_group_Handler),(r"/hosts_group/update", Hosts_groupUpdate_Handler),
            (r"/report", Report_Handler),(r"/report/line", ReportLine_Handler),(r"/report/nginx_access", ReportNginx_access_Handler),
            (r"/delete/(.*)/(.*)", Delete_Handler),
            (r"/test", test_Handler),
            (r"/test2", test2_Handler),
           # (r".*", MainHandler),
        ]
        settings = {
            "cookie_secret": "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=",
            "login_url":"/login",
            'template_path':os.path.join(os.path.dirname(__file__), 'templates'),
            'static_path' :os.path.join(os.path.dirname(__file__), 'static'),
            'debug':False
        }
        tornado.web.Application.__init__(self, handlers, **settings)

def check_login(fn):
    """验证登陆，如果没有登陆，则跳转到login页面"""
    def BtnPrv(self,*args,**kw):
        if not self.get_secure_cookie("user") or not self.get_secure_cookie("userid"):
            return self.redirect('/login')
        return fn(self,*args,**kw)
    return BtnPrv

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")

#class BaseHandler(tornado.web.RequestHandler):
#    def initialize(self):
#        redis = self.application.redis
#        self.session = self.application.SessionHandler(self, redis, session_lifetime=20)
#        self.current_password = self.session.password

#    def get_current_user(self):
#        return self.get_secure_cookie("username")
#=====================================================
class RequestHandler(BaseHandler):
    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.render('404.html')
        elif status_code == 500:
            self.render('500.html')
        else:
            super(RequestHandler, self).write_error(status_code, **kwargs)

class MainHandler(BaseHandler):
    #@tornado.web.asynchronous
    #@tornado.gen.engine
    #@tornado.web.authenticated
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("index")
        data=[]
        self.render('index/index.html',data=data,username=username,men_list=men)

class Rsync_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        res=[]
        upload_path='static/upload'
        #注意路径是否正确；
        file_list=os.listdir(upload_path)
        for i in file_list:
            file_path = upload_path+'/'+str(i.split()[0])
            s = os.path.getmtime(file_path)
            tt=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime( float(s)))
            res.append([i,os.path.getsize(file_path),tt])
        #print(res)
        men=main_men.men("rsync")
        self.render('rsync/index.html',res=res,username=username,men_list=men)

    @tornado.web.authenticated
    def post(self):
        upload_path='static/upload'
        cmd = self.get_argument('cmd')
        #判断是否上传文件
        if cmd == 'upload':
            try:
                f = self.request.files['file']
            except:
                self.redirect('/rsync')
            for meta in f:
                filename=meta['filename']
                filepath=os.path.join(upload_path,filename)
                with open(filepath,'wb') as up:      #有些文件需要已二进制的形式存储，实际中可以更改
                    up.write(meta['body'])
            self.redirect('/rsync')
        #判断是否删除文件
        if cmd == 'remove':
            args = self.request.arguments
            if 'filename' not in args:
                self.redirect('/rsync')
            #filename = self.get_argument('filename')
            for i in args['filename']:
                #print(i.decode())
                filename = i.decode()
                filepath=os.path.join(upload_path,filename)
                if os.path.isfile(filepath):
                    os.remove(filepath)
            self.redirect('/rsync')

class Rsync_file_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        men=main_men.men("rsync")
        file_list = []
        path = './static/upload/'
        for i in os.listdir(path):
            if os.path.isfile(path + i):file_list.append(i)
        res = file_list
        self.render('rsync/rsync_file.html',res=res,username=username,men_list=men)

    def post(self):
        args = self.request.arguments
        #print(args)
        if "filename" not in args:
            return self.redirect('/rsync/file')

        if args['cmd'][0].decode('utf8') == 'rsync':
            for i in args['filename']:
                rsync_sh='rsync.sh %s'%i.decode('utf8')
                print(rsync_sh)
                #os.popen(rsync_sh)

        elif args['cmd'][0].decode('utf8') == 'update_rsync':
            for i in args['filename']:
                rsync_update_sh = 'rsync_update.sh %s' % i.decode('utf8')
                print(rsync_update_sh)
                # os.popen(rsync_sh)

        return self.redirect('/rsync/file')

class Rsync_dir_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        dir_list=[]
        username = self.get_secure_cookie("user")
        men = main_men.men("rsync")
        path='./rsync/'
        for i in os.listdir(path):
            if os.path.isdir(path+i):
                dir_list.append(i)

        d_type=list(mysql.read('select id,gname from hosts_group;'))
        sqls = '''
            select a.id,a.hip,a.hgid,a.hport,a.huser,a.hpasswd,a.hstatus,a.monit,b.gname
            from hosts as a
            LEFT JOIN hosts_group as b
            ON a.hgid = b.id
            where 1=%s
            '''
        res = list(mysql.read(sqls, 1))
        dd = {}
        for i in res:
            if i[2] in dd:
                #dd[i[2]]['name']=i[-1]
                dd[i[2]]['data'].append(i[1])
            else:
                dd[i[2]] = {'name':i[-1],'data':[i[1]]}

        self.render('rsync/rsync_dir.html',res=dir_list,dd=dd,username=username,men_list=men,d_type=d_type)
        #self.render('rsync/rsync_dir.html',**locals())


    @check_login
    def post(self):
        args = self.request.arguments #获取所以数据
        d_group=self.get_argument('d_group',0)
        d_host = self.get_argument('d_host',0)
        print(d_group,d_host)
        if "filename" not in args or not d_host or not d_group:
            return self.redirect('/rsync/dir')

        if args['cmd'][0].decode('utf8') == 'rsync':
            for i in args['filename']:
                i = i.decode('utf8')
                if d_host == 'all':
                    sqls = 'select hip,hport from hosts where hgid=%s'
                    res = list(mysql.read(sqls, d_group))
                    for n in res:
                        #rsync_sh = 'rsync -avzP --delete --password-file=rsync.password ./%s/*  ./%s' % (i, i)
                        rsync_sh='rsync -avzP --delete -e ssh -p %s   ./%s/*  root@%s:/%s'%(n[1],i,n[0],i)
                        print(rsync_sh)
                else:
                    rsync_sh = 'rsync -avzP --delete -e ssh -p 22   ./%s/*  root@%s:/%s' % ( i, d_host, i)
                    # os.popen(rsync_sh)

        if args['cmd'][0].decode('utf8') == 'update_rsync':
            for i in args['filename']:
                i = i.decode('utf8')
                if d_host == 'all':
                    sqls = 'select hip,hport from hosts where hgid=%s'
                    res = list(mysql.read(sqls, d_group))
                    for n in res:
                        #rsync_update_sh = 'rsync -au ./%s/   ./%s' % (i, i)
                        rsync_update_sh = 'rsync -au  -e ssh -p %s   ./%s/*  root@%s:/%s' % (
                        n[1], i, n[0], i)
                        print(rsync_update_sh)
                else:
                    rsync_update_sh = 'rsync -au -e ssh -p 22   ./%s/*  root@%s:/%s' % (i, d_host, i)
                    # os.popen(rsync_sh)
                    print(rsync_update_sh)
        return self.redirect('/rsync/dir')

class Zdh_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        men=main_men.men("zdh")
        return self.render('zdh/index.html',res=data,username=username,men_list=men)

class Zdh_server_Handler(BaseHandler):
    @check_login
    def get(self):
        men = main_men.men("zdh")
        username = self.get_secure_cookie("user")
        sql = '''
            select a.id,a.hip,a.hgid,a.hport,a.huser,a.hpasswd,a.hstatus,a.monit,b.gname
            from hosts as a
            LEFT JOIN hosts_group as b
            ON a.hgid = b.id
            where 1=%s
            '''
        res = list(mysql.read(sql, 1))
        dd = {}
        for i in res:
            if i[2] in dd:
                # dd[i[2]]['name']=i[-1]
                dd[i[2]]['data'].append(i[1])
            else:
                dd[i[2]] = {'name': i[-1], 'data': [i[1]]}
        return self.render('zdh/index.html',dd=dd,username=username,men_list=men)

    @check_login
    def post(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("zdh")
        args = self.request.arguments  # 获取所以得post值
        print(args)
        dst_before_op = int(args['dst_before_op'][0])
        dst_before_cmd =args['dst_before_cmd'][0].decode()
        dst_group = args['dst_group'][0].decode()
        dst_host = args['dst_host'][0].decode()
        dst_server = args['dst_server'][0].decode()
        dst_autostart = int(args['dst_autostart'][0])
        dst_after_op = int(args['dst_after_op'][0])
        dst_after_cmd = args['dst_after_cmd'][0].decode()
        if dst_group=='0' or dst_host=='0' or dst_server=='0':
            return self.redirect('/zdh/server')
        if dst_host=='1':
            sqls='select hip,hport from hosts where hgid=%s'
            res = list(mysql.read(sqls,dst_group))
            print(res)
            for i in res:
                dst_sh = './zdh/install.sh %s %s %s %s %s %s %s %s' % (dst_before_op, dst_before_cmd, dst_group, i[0], dst_server, dst_autostart, dst_after_op,dst_after_cmd)
                print(dst_sh)
        else:
            dst_sh = './zdh/install.sh %s %s %s %s %s %s %s %s' % (dst_before_op, dst_before_cmd, dst_group, dst_host, dst_server, dst_autostart, dst_after_op, dst_after_cmd)
            # status=os.popen(dst_sh)
            print(dst_sh)
        return self.redirect('/zdh/server')

class Zdh_docker_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        men=main_men.men("zdh")
        return self.render('zdh/index.html',res=data,username=username,men_list=men)

class Check_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        men=main_men.men("check")
        self.render('check/index.html',res=data,username=username,men_list=men)

    #@tornado.web.authenticated
    @check_login
    def post(self):
        username = self.get_secure_cookie("user")
        data=[]
        hostlist=[]
        res=mysql.read("select hip,hport  from hosts where monit='1'")
        hostlist.extend([list(i) for i in res])
        data.extend(ch_tpp.run(hostlist))
        #print(data)
        men=main_men.men("check")
        self.render('check/index.html',res=data,username=username,men_list=men)

class CheckHost_Handler(BaseHandler):
    #@tornado.web.asynchronous
    #@tornado.gen.engine
    #@tornado.web.authenticated
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        ips=[]
        res=mysql.read("select *,count(distinct ip) from hostinfo group by ip")
        for i in res:
            ips.append(list(i))
        #print(ips)
        #men_js=json.load(open('conf/men.json','r'))
        men=main_men.men("check")
        #print(men)
        self.render('check/host.html',ips=ips,username=username,men_list=men)

class CheckInfo_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        tms=[]
        data=[]
        cpu_data=[]
        ip = [self.get_argument('ip')]
        sqls="select * from hostinfo where time >= UNIX_TIMESTAMP(date_sub(curdate(), INTERVAL 7 DAY)) and ip=%s"
        sqls="select * from hostinfo where ip=%s"
        #res=mysql.read("select * from hostinfo where ip=%s",ip)
        res=mysql.read(sqls,ip)
        res=list(res)
        for i in res:
            i=list(i)
            #print(i)
            ts=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(i[2]))
            tms.append(ts)
            data.append([ts,i[4:]])
            cpu_data.append(i[3])
        #print(data,cpu_data)
        men=main_men.men("check")
        self.render('check/info.html',data=data,ips=ip,tms=tms,cpu_data=cpu_data,username=username,men_list=men)

class Users_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        sql='''
            select a.id,a.name,a.email,a.status,a.phone,b.gname as qx,a.zc
            from users as a
            LEFT JOIN users_role as b
            ON a.qx = b.id
        '''
        res=mysql.read(sql)
        res=list(res)
        for i in res:
            i=list(i)
            data.append(i)
        men=main_men.men("users")
        self.render('users/index.html',data=data,username=username,men_list=men)

class UsersAdd_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        res = mysql.read("select id,gname from users_role;")
        res = list(res)
        men=main_men.men("users")
        self.render('users/add.html',username=username,data=res,men_list=men)

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument('name')
        passwd = self.get_argument('passwd')
        email = self.get_argument('email')
        status = self.get_argument('status')
        phone = self.get_argument('phone')
        qx = self.get_argument('qx')
        zc=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        res = mysql.read("select count(name) from users where email='%s' limit 1;"%name)
        res = list(res)
        if res[0][0] != 0:
            self.redirect('/users/add')
        else:
            try:
                sqls = "insert into  `users` (name,passwd,email,status,phone,qx,zc) values('%s','%s','%s','%s','%s','%s','%s');"
                mysql.write(sqls%(name,passwd,email,status,phone,qx,zc))
                self.redirect('/users')
            except:
                self.redirect('/users/add')

class UsersUpdate_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("users")
        self.res=[]
        id = self.get_argument('id',None)
        #print(id,type(id))
        if id == None:
            self.redirect('/users')

        sql='''
            select a.id,a.name,a.passwd,a.email,a.status,a.phone,a.qx,b.gname
            from users as a
            LEFT JOIN users_role as b
            ON a.qx = b.id
            where a.id=%s
            '''
        res=mysql.read(sql,[int(id)])
        res=list(res)
        #print(res)
        #userupdate_res.extend(res)
        self.res.extend(res)

        res2 = mysql.read("select id,gname from users_role;")
        res2 = list(res2)
        #print(res[0][0],res[0][1])
        self.render('users/update.html',data=res,data2=res2,username=username,men_list=men)

    @tornado.web.authenticated
    def post(self):
        id = self.get_argument('id')
        cmd = self.get_argument('cmd')
        name = self.get_argument('name')
        passwd = self.get_argument('passwd')
        email = self.get_argument('email')
        status = self.get_argument('status')
        phone = self.get_argument('phone')
        qx = self.get_argument('qx')
        #print(name,passwd,email,phone,qx)
        if cmd == 'false':
            self.redirect('/users')
        if cmd == 'update':
            sqls="update  `users` set name=%s,passwd=%s,email=%s,status=%s,phone=%s,qx=%s where id=%s;"
            status=mysql.write(sqls,[name,passwd,email,status,phone,qx,id])
            if status:
                self.redirect('/users')

class Users_group_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        res=mysql.read("select id,gname from users_role")
        res=list(res)
        for i in res:
            i=list(i)
            data.append(i)

        men=main_men.men("users")
        self.render('users/group.html',data=data,username=username,men_list=men)

    def post(self):
        name = self.get_argument('groupname')
        res = mysql.read("select count(gname) from users_role where gname=%s limit 1;",[name])
        res = list(res)
        #print(res)
        if res[0][0] != 0:
            self.redirect('/users_group')
        else:
            sqls = "insert into  `users_role` (gname) values(%s);"
            mysql.write(sqls,name)
        self.redirect('/users_group')

class Users_groupUpdate_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        self.res=[]
        id = self.get_argument('id',None)
        #print(id,type(id))
        if id == None:
            self.redirect('/users_role')
        res=mysql.read("select id,gname from users_role where id=%s",[int(id)])
        res=list(res)
        userupdate_res.extend(res)
        self.res.extend(res)
        #print(res[0][0],res[0][1])
        men=main_men.men("users")
        self.render('users/group_update.html',data=res,username=username,men_list=men)


    def post(self):
        id = self.get_argument('id')
        cmd = self.get_argument('cmd')
        name = self.get_argument('groupname')
        #print(name,passwd,email,phone,qx)
        #print(self.request.arguments)
        if cmd == 'false':
            self.redirect('/users_group')
        if cmd == 'update':
            sqls="update  `users_role` set gname=%s where id=%s;"
            mysql.write(sqls,[name,id])
        self.redirect('/users_group')


#主机和主机组
class Hosts_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        sql = '''
            select a.id,a.hip,b.gname,a.hport,a.huser,a.hpasswd,a.hstatus,a.monit
            from hosts as a
            LEFT JOIN hosts_group as b
            ON a.hgid = b.id
            '''
        res=list(mysql.read(sql))
        #print(res)
        for i in res:
            i=list(i)
            data.append(i)

        men=main_men.men("hosts")
        self.render('hosts/index.html',data=data,username=username,men_list=men)

class HostsAdd_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("hosts")
        sql = 'select id,gname from hosts_group'
        res = list(mysql.read(sql))
        self.render('hosts/add.html',username=username,men_list=men,data=res)

    @check_login
    def post(self):
        hip = self.get_argument('hip')
        hgid = self.get_argument('hgroup')
        hport = self.get_argument('hport')
        huser = self.get_argument('huser')
        hpasswd = self.get_argument('hpasswd')
        hstatus = self.get_argument('hstatus')
        monit = self.get_argument('monit')
        #print(hip,hgroup,hport,huser,hpasswd,hstatus)
        res=mysql.read("select count(hip) from hosts where hip=%s limit 1;",hip)
        res =list(res)
        if res[0][0] == 0:
            sqls = "insert into  `hosts` (hip,hgid,hport,huser,hpasswd,hstatus,monit) values(%s,%s,%s,%s,%s,%s,%s);"
            mysql.write(sqls,[hip,hgid,hport,huser,hpasswd,hstatus,monit])
        self.redirect('/hosts')

class HostsUpdate_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("hosts")
        #global hostupdate_res
        #hostupdate_res=[]
        id = self.get_argument('id',None)
        if id == None:
            return self.redirect('/hosts')
        #print(id)
        sql = '''
            select a.id,a.hip,a.hgid,a.hport,a.huser,a.hpasswd,a.hstatus,a.monit,b.gname
            from hosts as a
            LEFT JOIN hosts_group as b
            ON a.hgid = b.id
            where a.id=%s
            '''
        res  = list(mysql.read(sql, int(id)))
        res2 = list(mysql.read("select id,gname from hosts_group;"))
        #print(res2)
        dd = {}
        for i in res2:
            dd[i[1]] = []
        for i in res:
            print(i)
            if i[-1] in dd:
                dd[i[-1]].append(i[1])
            else:
                dd[i[-1]]=[]

        print(dd)
        self.render('hosts/update.html',username=username,men_list=men,data=res,data2=res2)

    def post(self):
        cmd = self.get_argument('cmd')
        id = self.get_argument('id')
        hip = self.get_argument('hip')
        hgid = self.get_argument('hgroup')
        hport = self.get_argument('hport')
        huser = self.get_argument('huser')
        hpasswd = self.get_argument('hpasswd')
        hstatus = self.get_argument('hstatus')
        monit = self.get_argument('monit')
        print(cmd,type(cmd))
        if cmd == 'update':
            sqls = "update  `hosts` set hip=%s,hgid=%s,hport=%s,huser=%s,hpasswd=%s,hstatus=%s,monit=%s where id=%s;"
            mysql.write(sqls,(hip, hgid, hport, huser, hpasswd, hstatus, monit, id) )
        if cmd == 'add':
            sqls = "insert into  `hosts` (hip,hgroup,hport,huser,hpasswd,hstatus,monit) values(%s,%s,%s,%s,%s,%s,%s);"
            mysql.write(sqls, [hip, hgid, hport, huser, hpasswd, hstatus, monit])
        return self.redirect('/hosts')
            #self.render('hosts_update.html',data=hostupdate_res)

class Hosts_group_Handler(BaseHandler):
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("hosts")
        data = []
        res = mysql.read("select id,gname from hosts_group")
        res = list(res)
        for i in res:
            i = list(i)
            data.append(i)

        self.render('hosts/group.html', data=data, username=username, men_list=men)

    def post(self):
        name = self.get_argument('groupname')
        res = mysql.read("select count(gname) from hosts_group where gname=%s limit 1;", [name])
        res = list(res)
        # print(res)
        if res[0][0] != 0:
            self.redirect('/hosts_group')
        else:
            sqls = "insert into  `hosts_group` (gname) values(%s);"
            mysql.write(sqls, name)
        self.redirect('/hosts_group')

class Hosts_groupUpdate_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("hosts")
        self.res=[]
        id = self.get_argument('id',None)
        #print(id,type(id))
        if id == None:
            self.redirect('/hosts_group')
        res=list(mysql.read("select id,gname from hosts_group where id=%s",int(id)))
        #print(res)
        self.res.extend(res)
        #print(res[0][0],res[0][1])

        self.render('hosts/group_update.html',data=res,username=username,men_list=men)


    def post(self):
        id = self.get_argument('id')
        cmd = self.get_argument('cmd')
        name = self.get_argument('groupname')
        #print(name,passwd,email,phone,qx)
        #print(self.request.arguments)
        if cmd == 'false':
            self.redirect('/hosts_group')
        if cmd == 'update':
            sqls="update  `hosts_group` set gname=%s where id=%s;"
            mysql.write(sqls,[name,id])
        self.redirect('/hosts_group')


class Delete_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self,arxg1,arxg2):
        print(arxg1,arxg2)
        params=[arxg1,arxg2]
        #ip = self.get_argument('ip')
        mysql.write("delete  from %s where id=%s"%(arxg1,arxg2))
        if arxg1=='users_role':
            self.redirect('/users_group')
        else:
            self.redirect('/%s'%arxg1)

class UserDelete_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self,id):
        mysql.write("delete  from users where id=%s",id)
        self.redirect('/user')

class Report_Handler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        username = self.get_secure_cookie("user")
        men=main_men.men("report")
        self.render('report/index.html',username=username,men_list=men)

class ReportLine_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        men = main_men.men("report")
        self.render('report/line.html',username=username,men_list=men)

class ReportNginx_access_Handler(BaseHandler):
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        tms=[]
        data=[]
        total_number=[]
        #ip = self.get_argument('ip')
        sqls="select * from `nginx_access` where time >= UNIX_TIMESTAMP(date_sub(curdate(), INTERVAL 7 DAY)) and 1=%s"
        sqls="select * from `nginx_access`"
        res=mysql.read(sqls)
        res=list(res)
        for i in res:
            i=list(i)
            #print(i)
            ts=time.strftime("%Y-%m-%d %H:%M",time.localtime(i[1]))
            #ts=time.strftime("%Y-%m-%d %H:%M",time.gmtime(1460734161))
            tms.append(ts)
            data.append([ts,i[2:]])
            total_number.append(i[-1])
        #print(data)
        men=main_men.men("report")
        self.render('report/nginx_access.html',data=data,tms=tms,total_number=total_number,username=username,men_list=men)

class login_Handler(BaseHandler):
    def get(self):
        uid=self.get_secure_cookie("userid")
        uname=self.get_secure_cookie("user")
        if uid and uname:
            self.redirect('/')
        self.render('login.html',message='')

    def post(self):
        uname = self.get_argument('uname')
        upasswd = self.get_argument('upasswd')
        remember= self.get_argument('remember',None)
        #if not uname or not upasswd:message = '帐号或密码不能为空！'
        #    self.render('comm_login.html',message=message)
        ip=self.request.remote_ip
        try:
            res=mysql.read("select id,name,status from users where email=%s and passwd=%s  limit 1;",[uname,upasswd])
            uid=str(res[0][0])
            name=str(res[0][1])
        except:
            uid=0
        if res and res[0][2] !=0:
            if remember:
                self.set_secure_cookie("userid", str(res[0][0]),expires=time.mktime(time.localtime())+604800)
                self.set_secure_cookie("user", res[0][1],expires=time.mktime(time.localtime())+604800)
            else:
                self.set_secure_cookie("userid", str(res[0][0]),expires_days=None)
                self.set_secure_cookie("user", res[0][1],expires_days=None)
            sql="insert into  `users_log` (uid,user,type,status,messge,ipaddr) values(%s,%s,%s,%s,%s,%s);"
            mysql.write(sql,[int(uid),name,1,1,'登入成功',ip])
            self.redirect('/')
        else:
            message="账号或密码错误，请重新登陆！"
            sql="insert into  `users_log` (uid,user,type,status,messge,ipaddr) values(%s,%s,%s,%s,%s,%s);"
            mysql.write(sql,[int(uid),uname,1,0,'登入失败',ip])
            self.render('login.html',message=message)

class logout_Handler(BaseHandler):
    #@tornado.web.authenticated
    @check_login
    def get(self):
        uid=self.get_secure_cookie("userid").decode("utf8")
        uname=self.get_secure_cookie("user").decode("utf8")
        ip=self.request.remote_ip
        sql="insert into  `users_log` (uid,user,type,status,messge,ipaddr) values(%s,%s,%s,%s,%s,%s);"
        mysql.write(sql,[int(uid),uname,2,1,'--登出成功',ip])
        self.set_secure_cookie("userid", '')
        self.set_secure_cookie("user", '')
        self.redirect('/login')

class Logs_Handler(BaseHandler):
    #@tornado.web.asynchronous
    #@tornado.gen.engine
    #@tornado.web.authenticated
    @check_login
    def get(self):
        username = self.get_secure_cookie("user")
        data=[]
        res=mysql.read("select * from users_log limit 250")
        for i in res:
            data.append(list(i))
        stime=""
        dtime=""
        men=main_men.men("index")
        self.render('index/logs.html',data=data,username=username,men_list=men,stime=stime,dtime=dtime)

    @check_login
    def post(self):
        username = self.get_secure_cookie("user")
        data=[]
        cmd = self.get_argument("cmd")
        wherestr="WHERE 1=1"
        if cmd == 'serach':
            stime=self.get_argument("stime",None)
            if stime and stime is not None:
                wherestr=' '.join((wherestr,'AND tm >= "%s"'%stime))

            dtime=self.get_argument("dtime",None)
            if dtime and dtime is not None:
                wherestr=' '.join((wherestr,'AND tm <= "%s"'%dtime))
            sqls='''
                select * from users_log {where}
            '''.format(where=wherestr)
            #print(wherestr)
            res=mysql.read(sqls)
            for i in res:
                data.append(list(i))

            men=main_men.men("index")
            self.render('index/logs.html',data=data,username=username,men_list=men,stime=stime,dtime=dtime)
        else:
            return self.redirect('/logs')


#========================================================
class test_Handler(BaseHandler):
    def get(self):
        #res=testdb.write('INSERT INTO `kkk`.`users_group` (`groupname`) VALUES ("test1");')
        #print(res)
        self.render('test.html')

class test2_Handler(BaseHandler):
    def get(self):
        #res=testdb.read('select * from nginx_access')
        #mysql.commit()
        #print(res)
        self.render('index.html')

if __name__ == "__main__":
    #define("port", default=8000, help="run on the given port", type=int)
    #tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(myapp(),xheaders=True)
    #http_server.listen(options.port)
    http_server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
    #-----------------------------------------
    #app = myapp()
    #app.listen(8000)
    #app.redis = client.Redis()
    #app.SessionHandler = SessionHandler
    #tornado.ioloop.IOLoop.instance().start()
    #------------------------------------------

